package models

import (
	"github.com/beego/beego/v2/client/orm"
	"weiboxs.com/new_h_glasses/utils"
)

type ErpFlowing struct {
	Id           int64
	DepartmentId int64
	Typeid       int //类型1采购入库2冲红出库3退货出库4报损出库5盘盈入库6盘亏出库7销售出库
	Entry        *ErpEntry `orm:"rel(fk);null;on_delete(do_nothing)"`
	Number       string //单据号
	NumberUpNo   string //上级单据号
	FlowingUser  string
	FlowingNum   int64 //入库数量
	FlowingDate  int64
	IsFlushing   int //是否冲红1是2否
}

func (a *ErpFlowing) TableName() string {
	return ErpFlowingTableName()
}
func ErpFlowingTableName() string {
	return TableName("erp_flowing")
}

//查询
type ErpFlowingQueryParam struct {
	BaseQueryParam
	EntryNumber   string        `json:"entry_no"`
	FlowingNumber string        `json:"flowing_no"`
	FlowingUser   string        `json:"flowing_user"`
	EntryUser     string        `json:"entry_user"`
	StartDate     string        `json:"start_date"`
	EndDate       string        `json:"end_date"`
	DepartmentId  int64         `json:"depid"`
	IsFlushing    int           `json:"is_flushing"`
	Typeid        []interface{} `json:"typeid"`
}

func ErpFlowingPageList(params *ErpFlowingQueryParam, retate ...interface{}) ([]*ErpFlowing, int64) {

	ls := make([]*ErpFlowing, 0)
	query := orm.NewOrm().QueryTable(ErpFlowingTableName())
	if len(retate) > 0 {
		query = query.RelatedSel(retate...)
	}
	if len(params.EntryNumber) > 0 {
		query = query.Filter("Entry__number", params.EntryNumber)
	}
	if len(params.FlowingNumber) > 0 {
		query = query.Filter("PurchaseNo", params.FlowingNumber)
	}
	if len(params.FlowingUser) > 0 {
		query = query.Filter("FlowingUser", params.FlowingUser)
	}
	if len(params.EntryUser) > 0 {
		query = query.Filter("Entry__CreatedBy", params.EntryUser)
	}
	if len(params.StartDate) > 0 {
		query = query.Filter("FlowingDate__gte", utils.GetDateParse(params.StartDate))
	}
	if len(params.EndDate) > 0 {
		query = query.Filter("FlowingDate__lte", utils.GetDateParse(params.EndDate))
	}
	if len(params.Typeid) > 0 {
		query = query.Filter("typeid__in", params.Typeid...)
	}

	if params.IsFlushing > 0 {
		query = query.Filter("IsFlushing", params.IsFlushing)
	}
	query = query.Filter("department_id", params.DepartmentId)

	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&ls)

	return ls, total
}

//获取单条记录
func GeErpFlowingById(id int64) (*ErpFlowing, error) {
	r := new(ErpFlowing)
	err := orm.NewOrm().QueryTable(ErpFlowingTableName()).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}
